﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DmxInterface {

	/// <summary>Represents a DMX universe, with a number of channels and individual values for each of them.</summary>
	public class Universe {

		public const int StandardUniverseSize = 512;

		volatile byte[] _currentValues;


		public Universe() {
			_currentValues = new byte[StandardUniverseSize];
		}

		#region Value Change

		/// <summary>Gets or sets the value of a channel (0 based numbering).</summary>
		/// <param name="index">Channel index, starting from 0.</param>
		public byte this[int index] {
			get {
				return _currentValues[index];
			}
			set {
				_currentValues[index] = value;

				OnValueChange(index, value);
			}
		}


		public delegate void ValueChangeHandler(object sender, ValueChangeEventArgs e);

		public event ValueChangeHandler ValueChange;

		protected virtual void OnValueChange(int index, byte value) {
			if (ValueChange != null) {
				ValueChange(this, new ValueChangeEventArgs(index, value));
			}
		}

		public class ValueChangeEventArgs : EventArgs {

			public ValueChangeEventArgs(int index, byte value) {
				this.index = index;
				this.newValue = value;
			}

			int index;
			byte newValue;

			public int Index {
				get { return index; }
			}

			public byte NewValue {
				get {
					return newValue;
				}
			}
		}

		#endregion

		#region Reset

		public void Reset() {
			Array.Clear(_currentValues, 0, _currentValues.Length);

			OnValuesReset();
		}

		public event EventHandler ValuesReset;

		protected virtual void OnValuesReset() {
			if (ValuesReset != null)
				ValuesReset(this, EventArgs.Empty);
		}

		#endregion

		#region Byte table interface

		public byte[] UniverseState {
			get {
				return _currentValues;
			}
		}

		#endregion

	}
}
